package com.xiechur.dao.impl;

import com.xiechur.dao.StudentDao;
import com.xiechur.model.Student;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dell on 2016/3/27.
 */

public class StudentDaoImpl extends JdbcDaoSupport implements StudentDao {


    //    private JdbcTemplate jdbcTemplate;
//
//    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
//        this.jdbcTemplate = jdbcTemplate;
//    }
//由于extends JdbcDaoSupport 里面已经有一个final set 的方法，改 return jdbcTemplate.update(sql, params);
    @Override
    public int addStudent(Student student) {
        String sql = "insert into t_student values(null,?,?)";
        Object[] params = new Object[]{student.getName(), student.getAge()};
//        return jdbcTemplate.update(sql, params);
        return getJdbcTemplate().update(sql, params);
    }

    @Override
    public int updateStudent(Student student) {
        String sql = "update t_student set name = ?,age = ? WHERE id = ?";
        Object[] params = new Object[]{student.getName(), student.getAge(), student.getId()};//按照顺序
//        return jdbcTemplate.update(sql, params);
        return getJdbcTemplate().update(sql, params);
    }

    @Override
    public int deleteStudent(int id) {
        String sql = "delete from t_student where id = ?";
        Object[] params = new Object[]{id};
//        return jdbcTemplate.update(sql, params);
        return getJdbcTemplate().update(sql, params);
    }


    @Override
    public List<Student> findStudent() {
        String sql = "select * from t_student";
        final List<Student> studentList = new ArrayList<Student>();
//        jdbcTemplate.query(sql, new RowCallbackHandler() {
        getJdbcTemplate().query(sql, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                Student student = new Student();
                student.setId(rs.getInt("id"));
                student.setName(rs.getString("name"));
                student.setAge(rs.getInt("age"));
                studentList.add(student);
            }
        });
        return studentList;
    }
}
